<template>
  <div style="width: calc(100vw); height: calc(100vh); ">
    <div id="vditor"></div>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, onUnmounted, ref, watch } from 'vue';
  import { useMessage } from 'naive-ui'
  import { getCurrentWindow } from '@tauri-apps/api/window';
  import { convertFileSrc, invoke } from '@tauri-apps/api/core';
  import * as event from "@tauri-apps/api/event";
  import { openPath } from '@tauri-apps/plugin-opener';
  import Vditor from 'vditor';
  import 'vditor/dist/index.css';

  //json缓存文件
  const editorData = ref("");
  const app = getCurrentWindow();
  const message = useMessage()
  const vditor = ref<Vditor | null>(null);

  let id = "";
  let title = "";
  let heading = "";
  let date = "";
  //let group_type = "";
  let group_id = "";


  function getFileName(filePath: string) : string {
    let split = filePath.split("\\");
    let fileName = split[split.length-1];
    return fileName;
  }

  event.listen("tauri://drag-drop", async (e) => {
    let p:any = e.payload;
    if (p.paths.length === 1) {
      let name = getFileName(p.paths[0])
      if (name.endsWith("jpg") || name.endsWith("png") || name.endsWith("JPG") || name.endsWith("PNG")) {
        vditor.value?.insertValue("![" + name + "](" + convertFileSrc(p.paths[0]) + ")")
      } else {
        vditor.value?.insertValue("[" + name + "](" + p.paths[0] + ")")
      }
    } else {
      for (let i=0; i < p.paths.length; i++) {
        let name = getFileName(p.paths[i])
        if (name.endsWith("jpg") || name.endsWith("png") || name.endsWith("JPG") || name.endsWith("PNG")) {
          vditor.value?.insertValue("![" + name + "](" + convertFileSrc(p.paths[i]) + ")")
        } else {
          vditor.value?.insertValue("[" + name + "](" + p.paths[i] + ")")
        }
      }
    }

  });




    // 清理监听
  onUnmounted(() => {
    window.removeEventListener('resize', () => {console.log(111);})
  })




  onMounted(async () => {

    const label = app.label;
    const eid = label.replace("editor-", "");
    let data:any = await invoke("get_info_by_id", { id: eid });
    if (data.is_success) {
      editorData.value = data.data.note_content;
      id = data.data.id;
      title = data.data.title;
      heading = data.data.heading;
      date = data.data.date;
      //group_type = data.data.group_type;
      group_id = data.data.group_id;
    }
    await app.show();
    
    vditor.value = new Vditor('vditor', {
      cdn: '/vditor',
      hint: {
        emojiPath: '/vditor'
      },
      value: editorData.value,
      icon: "material",
      height:window.innerHeight - 2,
      toolbar: [
      {
        name: 'outline',
        tipPosition: 's',
        tip: '大纲',
      },
      {
        hotkey: '⌘S',
        name: 'save',
        tipPosition: 's',
        tip: '保存',
        className: 'right',
        icon: '<svg width="128" height="128" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M40.3535 14.3535C40.7441 14.7441 40.7441 15.3772 40.3535 15.7678L20.7071 35.4142C20.3166 35.8047 19.6834 35.8047 19.2929 35.4142L9.64644 25.7678C9.25591 25.3772 9.25591 24.7441 9.64644 24.3535L10.7979 23.202C11.1865 22.8135 11.8157 22.8112 12.2071 23.197L20 30.8787L37.7929 13.2025C38.1838 12.8141 38.8152 12.8152 39.2048 13.2048L40.3535 14.3535Z" fill="#EE0A24"></path></svg>',
        async click () {
          let data:any = await invoke("update", { id: id, noteContent: vditor.value?.getValue(), title: title, heading: heading, date: date, groupId: group_id });
          if (data.is_success) {
            message.success(
              '保存成功'
            )
          }
        },
      },
      {
        name: 'export',
        tipPosition: 's',
        tip: '导出',
      },
      "|",
      {
        name: 'preview',
        tipPosition: 's',
        tip: '预览',
        click(key) {
          console.log(key)
        },
      },
      {
        name: 'emoji',
        tipPosition: 's',
        tip: '表情',
      },
      {
        name: 'headings',
        tipPosition: 's',
        tip: '标题',
      },
      {
        name: 'bold',
        tipPosition: 's',
        tip: '粗体',
      },
      {
        name: 'italic',
        tipPosition: 's',
        tip: '斜体',
      },
      {
        name: 'strike',
        tipPosition: 's',
        tip: '删除线',
      },
      {
        name: 'link',
        tipPosition: 's',
        tip: '链接',
      },
      "|",
      {
        name: 'list',
        tipPosition: 's',
        tip: '无需列表',
      },
      {
        name: 'ordered-list',
        tipPosition: 's',
        tip: '有需列表',
      },
      {
        name: 'check',
        tipPosition: 's',
        tip: '任务列表',
      },
      {
        name: 'outdent',
        tipPosition: 's',
        tip: '任务反向缩进',
      },
      {
        name: 'indent',
        tipPosition: 's',
        tip: '任务缩进',
      },
      "|",
      {
        name: 'quote',
        tipPosition: 's',
        tip: '引用',
      },
      {
        name: 'line',
        tipPosition: 's',
        tip: '分割线',
      },
      {
        name: 'code',
        tipPosition: 's',
        tip: '代码块',
      },
      {
        name: 'inline-code',
        tipPosition: 's',
        tip: '行内代码',
      },
      {
        name: 'table',
        tipPosition: 's',
        tip: '表格',
      },
      "|",
      {
        name: 'undo',
        tipPosition: 's',
        tip: '撤销',
      },
      {
        name: 'redo',
        tipPosition: 's',
        tip: '重做',
      }
      ],
      after: () => {
        vditor.value!.setValue(editorData.value);
        let toolbar = document.getElementsByClassName("vditor-toolbar");
        //vditor-toolbar__item
        let toolbar_item = document.getElementsByClassName("vditor-toolbar__item");

        if (window.innerWidth < 800) {
          toolbar.item(0)?.setAttribute('style',"padding-left:" + 0 + "px; ")
        } else {
          toolbar.item(0)?.setAttribute('style',"padding-left:" + ((window.innerWidth - 800)/2+30) + "px; ")
        }

        document.getElementById("vditor")?.setAttribute("style", "height:100%;");
        for (let i=0; i < toolbar_item.length; i++) {
          toolbar_item.item(i)?.setAttribute('style',"padding:0px")
        }
        for (let i=0; i < toolbar_item.length; i++) {
          toolbar_item.item(i)?.setAttribute('style',"padding:0px")
        }

        window.addEventListener("resize", () => {
          if (window.innerWidth < 800) {
            toolbar.item(0)?.setAttribute('style',"padding-left:" + 0 + "px; ")
          } else {
            toolbar.item(0)?.setAttribute('style',"padding-left:" + ((window.innerWidth - 800)/2+30) + "px; ")
          }          
        })


        watch(editorData, (_n, _o) => {
          vditor.value!.setValue(editorData.value);
        })

        
      },
      link:{
        isOpen:false,
        click:async (bom: Element) => {
          //console.log(bom.getAttribute("href"));
          let target = bom.getAttribute("href");
          if (target) {
            if (target.startsWith("http")) {
              //window.open(target);
              await openPath(target);
            } else {
              await openPath(target);
            }
          }
        }
      },
      upload: {
        handler:async (_files: File[]) => {
          let groupTypes:string = await invoke("save_clipboard_img");
          if (groupTypes) {
            vditor.value?.insertValue("![" + "截图" + "](" + convertFileSrc(groupTypes) + ")")
          }
          
          return "";
        }
      },
      mode:"wysiwyg",
      ctrlEnter: (test: String) => {
        console.log(test)
      },
      input:async (value: string) => {
        let data:any = await invoke("update", { id: id, noteContent: value, title: title, heading: heading, date: date, groupId: group_id });
        if (data.is_success) {
        }
      },
      preview: {
        markdown: {
          autoSpace: true
        },
        delay: 600,
        mode: "both",
        parse:(_: HTMLElement) =>{
          
        },
        transform:(html: string) => {
          return html;
        },
        theme:{
          current: "Dark",
          list: { "ant-design": "Ant Design", dark: "Dark", light: "Light", wechat: "WeChat" },
          path: '/vditor'
        }

      },

      i18n:{
        'alignCenter': '居中',
        'alignLeft': '居左',
        'alignRight': '居右',
        'alternateText': '替代文本',
        'bold': '粗体',
        'both': '编辑 & 预览',
        'check': '任务列表',
        'close': '关闭',
        'code': '代码块',
        'code-theme': '代码块主题预览',
        'column': '列',
        'comment': '评论',
        'confirm': '确定',
        'content-theme': '内容主题预览',
        'copied': '已复制',
        'copy': '复制',
        'delete-column': '删除列',
        'delete-row': '删除行',
        'devtools': '开发者工具',
        'down': '下',
        'downloadTip': '该浏览器不支持下载功能',
        'edit': '编辑',
        'edit-mode': '切换编辑模式',
        'emoji': '表情',
        'export': '导出',
        'fileTypeError': '文件类型不允许上传，请压缩后再试',
        'footnoteRef': '脚注标识',
        'fullscreen': '全屏切换',
        'generate': '生成中',
        'headings': '标题',
        'heading1': '一级标题',
        'heading2': '二级标题',
        'heading3': '三级标题',
        'heading4': '四级标题',
        'heading5': '五级标题',
        'heading6': '六级标题',
        'help': '帮助',
        'imageURL': '图片地址',
        'indent': '列表缩进',
        'info': '关于',
        'inline-code': '行内代码',
        'insert-after': '末尾插入行',
        'insert-before': '起始插入行',
        'insertColumnLeft': '在左边插入一列',
        'insertColumnRight': '在右边插入一列',
        'insertRowAbove': '在上方插入一行',
        'insertRowBelow': '在下方插入一行',
        'instantRendering': '即时渲染',
        'italic': '斜体',
        'language': '语言',
        'line': '分隔线',
        'link': '链接',
        'linkRef': '引用标识',
        'list': '无序列表',
        'more': '更多',
        'nameEmpty': '文件名不能为空',
        'ordered-list': '有序列表',
        'outdent': '列表反向缩进',
        'outline': '大纲',
        'over': '超过',
        'performanceTip': '实时预览需 ${x}ms，可点击编辑 & 预览按钮进行关闭',
        'preview': '预览',
        'quote': '引用',
        'record': '开始录音/结束录音',
        'record-tip': '该设备不支持录音功能',
        'recording': '录音中...',
        'redo': '重做',
        'remove': '删除',
        'row': '行',
        'spin': '旋转',
        'splitView': '分屏预览',
        'strike': '删除线',
        'table': '表格',
        'textIsNotEmpty': '文本（不能为空）',
        'title': '标题',
        'tooltipText': '提示文本',
        'undo': '撤销',
        'up': '上',
        'update': '更新',
        'upload': '上传图片或文件',
        'uploadError': '上传错误',
        'uploading': '上传中...',
        'wysiwyg': '所见即所得',
      }

    });

    await app.setTitle(title + " - md");
  });
  
</script>
